package com.karry.yl.web.financial;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.NumberToCN;
import com.karry.commons.util.TimeUtil;
import com.karry.commons.vo.LayTableResponse;
import com.karry.yl.domain.financial.Receipt;
import com.karry.yl.domain.financial.ReceiptItems;
import com.karry.yl.domain.financial.SettlementRecords;
import com.karry.yl.service.financial.ReceiptItemsService;
import com.karry.yl.service.financial.ReceiptService;
import com.karry.yl.service.financial.SettlementRecordsService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收款单Controller
 */

@Controller
@RequestMapping("/settlementRecords")
public class SettlementRecordsController extends SuperController {

    @Autowired
    private SettlementRecordsService settlementRecordsService;
    @Autowired
    private ReceiptService receiptService;
    @Autowired
    private ReceiptItemsService receiptItemsService;

    @RequestMapping
    public String listUI() {
        return "financial/settlementrecords/list";
    }

    @RequestMapping("/list")
    @ResponseBody
    public LayTableResponse listUI(int page, int limit) {
        Page<SettlementRecords> dataPage = settlementRecordsService.selectPage(new Page<SettlementRecords>(page, limit), new EntityWrapper<SettlementRecords>().eq("orgId", currentUser.getOrgId()).eq("deleted", false).orderBy("createdTime",false));
        return new LayTableResponse(dataPage.getRecords(), dataPage.getTotal());
    }

    @RequestMapping("/info")
    public String detail(Long id, ModelMap map) {
        SettlementRecords settlementRecords = settlementRecordsService.selectById(id);
        //获取该老人的所有的未支付 收费单
        map.put("curr", System.currentTimeMillis());  //结算账单的时间
        List<Receipt> receipts = receiptService.selectList(new EntityWrapper<Receipt>().in("id", settlementRecords.getReceiptIds()));
        Map<String,Integer> fwsf = new HashMap<>();
        Map<String,Integer> tcsf = new HashMap<>();
        Map<String,Integer> qtsf = new HashMap<>();
        BigDecimal fwsfSum = new BigDecimal("0");
        BigDecimal tcsfSum = new BigDecimal("0");
        BigDecimal qtsfSum = new BigDecimal("0");
        map.put("receipts", receipts);
        for (Receipt r : receipts) {
                List<ReceiptItems> items = receiptItemsService.selectList(new EntityWrapper<ReceiptItems>().eq("receiptId", r.getId()).eq("deleted", false));
                r.setReceiptItemsList(items);
                if(r.getType() == 2){
                    if(!tcsf.containsKey("￥" + r.getAmount()+"/"+r.getName())){
                        tcsf.put("￥" + r.getAmount()+"/"+r.getName(),1);
                    }else {
                        tcsf.put("￥" + r.getAmount()+"/"+r.getName(),tcsf.get("￥" + r.getAmount()+"/"+r.getName()) + 1);
                    }
                    tcsfSum = tcsfSum.add(r.getAmount());
                }
                for(ReceiptItems item : items){
                    if(r.getType() == 1){
                        if(!fwsf.containsKey("￥" + r.getAmount()+"/"+item.getName())){
                            fwsf.put("￥" + r.getAmount()+"/"+item.getName(),1);
                        }else {
                            fwsf.put("￥" + r.getAmount()+"/"+item.getName(),fwsf.get("￥" + r.getAmount()+"/"+item.getName()) + 1);
                        }
                        fwsfSum = fwsfSum.add(r.getAmount());
                    }else{
                        if(!qtsf.containsKey(item.getName())){
                            qtsf.put("￥" + r.getAmount()+"/"+item.getName(),1);
                        }else {
                            qtsf.put("￥" + r.getAmount()+"/"+item.getName(),qtsf.get("￥" + r.getAmount()+"/"+item.getName()) + 1);
                        }
                        qtsfSum = qtsfSum.add(r.getAmount());
                    }
                }
        }
        map.put("dxSettleAmount",NumberToCN.number2CNMontrayUnit(settlementRecords.getSettleAmount()));
        map.put("fwsf",fwsf);
        map.put("tcsf",tcsf);
        map.put("qtsf",qtsf);

        map.put("fwsfSum",fwsfSum);
        map.put("tcsfSum",tcsfSum);
        map.put("qtsfSum",qtsfSum);
        map.put("settlementRecords",settlementRecords);
        return "financial/settlementrecords/info";
    }

    /**
     * 结算记录导出为excel
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("/export/excel")
    public void exportExcel(HttpServletResponse response) {
        //查询所有的巡检记录
        List<SettlementRecords> settlementRecords = settlementRecordsService.selectList(new EntityWrapper<SettlementRecords>().eq("orgId", currentUser.getOrgId()));
        //生成Excel,并存储临时文件
        // 创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("结算记录");

        // 表头
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式

        //声明列对象
        HSSFCell cell = null;

        //创建标题
        String[] title = {"所属老人", "身份证号", "结算金额", "结算时间 "};
        for (int i = 0; i < title.length; i++) {
            row.setHeightInPoints(20);
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
            sheet.setColumnWidth(i, 21 * 256);
        }

        //创建内容
        for (int i = 0; i < settlementRecords.size(); i++) {
            row = sheet.createRow(i + 1);
            row.setHeightInPoints(20);
            SettlementRecords settlementRecords1 = settlementRecords.get(i);
            row.createCell(0).setCellValue(settlementRecords1.getElderlyName());
            row.createCell(1).setCellValue(settlementRecords1.getElderlyIdNo());
            row.createCell(2).setCellValue("¥"+settlementRecords1.getSettleAmount().toString());
            String format = TimeUtil.format(settlementRecords1.getSettleTime(), "yyyy-MM-dd HH:mm:ss");
            row.createCell(3).setCellValue(format);
        }

        //下载
        response.setCharacterEncoding("UTF-8");
        try (ServletOutputStream out = response.getOutputStream();) {
            response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("结算记录-" + TimeUtil.format(new Date(), "yyyyMMddHHmmss") + ".xls", "UTF-8"));
            wb.write(out);
        } catch (IOException e) {
            //TODO 下载失败日志记录
        } finally {
            try {
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
